package aspect;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import aop.MyLogger;

@Aspect
public class CalculatorLogAspect {
	private MyLogger logger=new MyLogger();
	
//	拦截所有的类的方法
	@Pointcut("execution(* *.*(..))")
	private void logOperation(){}//也可以放到公共类里去
	
	
	
//	@Before("execution(* calculator.IArithmeticCalculator.add(..))")
//	public void logBefore(){
//		logger.log("before add");
//	}
	
//	拦截所有的类的方法
//	@Before("logOperation()")//"logOperation()"调用方法的切入点
//	public void logBefore(JoinPoint joinPoint){
//		logger.log("{before}the method is "+joinPoint.getSignature().getName());
//		logger.log("args:"+Arrays.toString(joinPoint.getArgs()));
//	}
	
	@Before("LogPointcuts.logAdd()")
	public void logBefore(JoinPoint joinPoint){
		logger.log("{before}the method is "+joinPoint.getSignature().getName());
		logger.log("args:"+Arrays.toString(joinPoint.getArgs()));
	}
	
	@AfterReturning(
		pointcut="execution(* *.*(..))",
		returning="result"//与参数中一致
	)
	public void logAfterReturning(JoinPoint joinPoint,Object result){
		logger.log("{AfterReturning} method"+joinPoint.getSignature().getName());
		logger.log("result="+result);
	}
	
	
	@AfterThrowing(
		pointcut="execution(* *.*(..))",
		throwing="illegalArgumentException"
	)
	public void logThrowing(JoinPoint joinPoint,IllegalArgumentException illegalArgumentException){
		logger.log("{AfterThrowing} method:"+joinPoint.getSignature().getName());
		logger.log("exception:"+illegalArgumentException.getMessage());
	}
	
	@After("execution(* *.*(..))")
	public void logAfter(JoinPoint joinPoint){
		logger.log("{After} method:"+joinPoint.getSignature().getName());
	}
	
	
	
//	@Around("execution(* *.*(..))")
//	public Object logAround(ProceedingJoinPoint proceedingJoinPoint){
//		logger.log("{Around}Before Method:"+proceedingJoinPoint.getSignature().getName());
//		try {
//			Object result=proceedingJoinPoint.proceed();
//			logger.log("{Around}After Method:"+proceedingJoinPoint.getSignature().getName()+","+"result:"+result);
//			return result;
//		} catch (IllegalArgumentException e) {
//			logger.log("{Around}Exception:Illegal Argument"+Arrays.toString(proceedingJoinPoint.getArgs()));
//			throw e;
//		}
//	}
}
